Containers

Containers are set of objects including lists, sets, tuples, and dictionaries. They hold other variables in various different ways following different rules. These are arguably the most used, and most useful, objects you will encounter in today's course.

Lists

Lists are objects that hold variables in a particular order that you choose. They can hold any variable you wish, in fact, one list can hold more than one type of variable. Recall that our "basic" types are int, float, str, and bool. Let's see some examples of lists.


In [4]:
list1=[1,2,3,4]
print(list1)
list2=["a","b","c","d"]
print(list2)
list3=[True, False, True]
print(list3)
list3=[1,2,"c","d"]
print(list3)
list4=[2>3, 2, 4, 3>2]
print(list4)


[1, 2, 3, 4]
['a', 'b', 'c', 'd']
[True, False, True]
[1, 2, 'c', 'd']
[False, 2, 4, True]

Let's notice a few key things:

  1. To make a list we use []
  2. We separate individual elements with commas
  3. The elements of a list can be any type
  4. The elements need not be explicitly written

Other Properties of Lists

  1. You can add two lists to create a new list.
  2. You can append an element to the end of a list by using the append function.
  3. You can append a list to the end of another list by using the += operator.
  4. You can access a single element with something called slicing

In [9]:
la=[1,2,3]
lb=["1","2","3"]
print(la+lb)
la.append(4)
print(la)
lb+=la
print(lb)


[1, 2, 3, '1', '2', '3']
[1, 2, 3, 4]
['1', '2', '3', 1, 2, 3, 4]

Slicing

At one point, you will want to access certain elements of a list, this is done by slicing. There are a couple of ways to do this.

  1. la[0] will give the first element of the list la. Note that lists are indexed starting at zero, not one.
  2. la[n] will give the (n+1)th element of the list la.
  3. la[-1] will give the last element of the list la.
  4. la[-n] will give the nth to last element of the list la.
  5. la[p:q:k] will give you every kth element starting at p and ending at q of the list la. Ex/la[1:7:2] will give you every second element starting at 1 and ending at 7. 5b. If p is omitted, it is assumed to be 0. If k is omitted, it is assumed to be 1, if q is omitted, it is assumed to be the last index or -1, which is really the same thing as we see above.

In [11]:
la=[1,2,3,4,5,6,7,8,9,10]
print(la[0])
print(la[3])
print(la[-1])
print(la[-3])
print(la[0:10:2])
print(la[3::2])
print(la[2:4:])
print(la[2:4])


1
4
10
8
[1, 3, 5, 7, 9]
[4, 6, 8, 10]
[3, 4]
[3, 4]

Exercises

  1. Make 2 lists and add them together.

  2. Take your list from 1., append the list ["I", "Love", "Python"] to it without using the append command, then print every second element.

  3. Can you make a list of lists? Try it.

    Consider the list x=[3,5,7,8,"Pi"].

4a. Type out what you would expect python to print along with the type of object printed would be for the following slices:

x[2]

x[0]

x[-2]

x[1::2]

x[1::]

x[::-4]

4b. Check your answer by creating that list and printing out the corresponding slices.

Sets

Sets are a special type of list that adhere to certain rules. If you have taken any higher level or proof-based math classes, you will recognize that sets in Python are exactly the same as those in mathematics. Instead of using [], {} are used to create a set. Sets have the following properties:

  1. Sets will not contain duplicates. If you make a set with duplicates, it will only retain one of them.
  2. Sets are not ordered. This means no slicing.
  3. Sets have the familiar set operations from math. These are outlined below.
  4. You can convert a list to a set in the following manner: Let t be a list, then set(t) is now a set containing the elements of t.

Set Operations

Consider sets s={1,2,3} and t={1,2,3,4,5};

Operation Meaning Example
s|t Union {1,2,3,4,5}
s&t Intersection {1,2,3}
s-t Difference {}
s^t Symmetric Difference {4,5}
s<t Strict Subset True
s<=t Subset True
s>t Strict Superset False
s>= Superset False

In [17]:
t = {1,2,3,3,3,3,3,3,3,3,3,3,3,3,3,4,5}
print(t)
s = {1,4,5,7,8}
print(t-s)
print(s-t)
print(t^s)
print(t-s|s-t)
print(t^s==t-s|s-t)


{1, 2, 3, 4, 5}
{2, 3}
{8, 7}
{2, 3, 7, 8}
{8, 2, 3, 7}
True

Exercises

  1. Write a set containing the letters of the word "dog".
  2. Find the difference between the set in 1. and the set {"d", 5, "g"}
  3. Remove all the duplicates in the list [1,2,4,3,3,3,5,2,3,4,5,6,3,5,7] and print the resulting object in two lines.

Tuples

Tuples are just like lists except that you cannot append elements to a tuple. You may, however, combine two tuples. To create a tuple, one uses ().


In [18]:
a = (1,2,3,4,5)
b = ('a', 'b', 'c')
print(a)
print(b)
print(a+b)


(1, 2, 3, 4, 5)
('a', 'b', 'c')
(1, 2, 3, 4, 5, 'a', 'b', 'c')

Dictionaries

Dictionaries are quite different from any container we have seen so far. A dictionary is a bunch of unordered key/value pairs. That is, each element of a dictionary has a key and a value and the elements are in no particular order. It is good to keep this unorderedness in mind later on, for now, let's look at some examples. To create a dictionary we use the following syntax, { key:value}.


In [57]:
#Let's say we have some students take a test and we want to store their scores
scores = {'Sally':89, 'Lucy':75, 'Jeff':45, 'Jose':96}
print(scores)
#We can, however, not combine two different dictionaries
scores2 = {'Devin':64, 'John':23, 'Jake':75}
print(scores2)
print(scores+scores2)


{'Sally': 89, 'Jeff': 45, 'Lucy': 75, 'Jose': 96}
{'Jake': 75, 'John': 23, 'Devin': 64}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-57-07c4638eecae> in <module>()
      5 scores2 = {'Devin':64, 'John':23, 'Jake':75}
      6 print(scores2)
----> 7 print(scores+scores2)

TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

Unlike with lists, we cannot access elements of the dictionary with slicing. We must instead use the keys. Let's see how to do this.


In [58]:
print(scores['Sally'])
print(scores2['John'])


89
23

As we can see, the key returns us the value. This can be useful if you have a bunch of items that need to be paired together.

Accessing Just the Keys or Values

Want to get a list of the keys in a dictionary? How about the values? Fret not, there is a way!


In [68]:
print(scores.keys())
print(scores.values())


dict_keys(['Sally', 'Jeff', 'Lucy', 'Jose'])
dict_values([89, 45, 75, 96])

Exercises

  1. Build a dictionary of some constants in physics and math. Print out at least two of these values.
  2. Give an example of something that would be best represented by a dictionary, think pairs.

In and Not In

No, this section isn't about fashion. It is about the in and not in operators. They return a boolean value based on whether or not a value is in or not in a container. Note that for dictionaries, this refers to the keys, no the values.


In [62]:
print('Devin' in scores2)
print(2 in a)
print('Hello World' not in scores)


True
True
True

Converting Between Containers

But what if I want my set to be a list or my tuple to be a set? To convert between types of containers, you can use any of the following functions:

list() : Converts any container type into a list, for dictionaries it will be the list of keys.

tuple() : Converts any container type into a tuple, for dictionaries it will be the tuple of keys.

set() : Converts any container type into a set, for dictionaries it will be the set of keys. Note that as above, this will remove all duplicates.


In [77]:
a = [1,2,3]
b = (1,2,3)
c = {1,2,3}
d = {1:2,3:4}

print(list(b))
print(list(c))
print(list(d))

print(tuple(a))
print(tuple(c))
print(tuple(d))

print(set(a))
print(set(b))
print(set(d))


[1, 2, 3]
[1, 2, 3]
[1, 3]
(1, 2, 3)
(1, 2, 3)
(1, 3)
{1, 2, 3}
{1, 2, 3}
{1, 3}

Exercises

  1. Take the tuple (1,1,1,1,3,4,3,5,57,6,4,4,4,6,5,6) and remove its duplicates. Then turn it into a list.
  2. Earlier we saw that you could retrieve the keys and values of a dictionary individually, but they weren't lists yet. Using the dictionary d = {'tall':624, 'short':234, 'Feynman':'diagrams', 'dead':'cat', 'alive':'cat'}, try converting the keys and values into lists and print them out.
  3. Consider a = [1,2,3,4,5] and b = ['a','b','c','p'] is 'p' in a+b? Is 34 in a+b? Write a boolean statement the is true involving 34 and a+b.

In [ ]: